package com.breaktian.network.download;




import com.breaktian.assemble.utils.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by breaktian on 2016/9/21.
 */
public class HttpDownload {

	private static HttpDownload instance;

	private final static Object lockObj = new Object();
	private final ExecutorService threadPool;

	public static HttpDownload get() {
		if (instance == null) {
			synchronized (lockObj) {
				if (instance == null) {
					instance = new HttpDownload();
				}
			}
		}
		return instance;
	}

	private HttpDownload() {
		int size = Runtime.getRuntime().availableProcessors();
		threadPool = Executors.newFixedThreadPool(size * 2);
	}

	public void downloadFile(String url, File file, DownLoadListener listener) {
		threadPool.execute(new DownloadTask(url, file, listener));
	}

	class DownloadTask implements Runnable {

		private final String url;
		private final File file;
		private final DownLoadListener listener;

		public DownloadTask(String url, File file, DownLoadListener listener) {
			this.url = url;
			this.file = file;
			this.listener = listener;
		}

		@Override
		public void run() {
			FileOutputStream outputStream = null;
			InputStream inputStream = null;
			try {
				URL mUrl = new URL(url);
				HttpURLConnection httpURLConnection = (HttpURLConnection) mUrl.openConnection();
				httpURLConnection.setConnectTimeout(300 * 1000);// 30秒超时
				inputStream = httpURLConnection.getInputStream();
				// int totalSize = inputStream.available();
				int totalSize = httpURLConnection.getContentLength();
				outputStream = new FileOutputStream(file);
				byte[] buf = new byte[1024 * 100];
				int readSize = 0;
				LogUtil.d("totalSize:" + totalSize);
				while (readSize < totalSize) {
					int read = inputStream.read(buf);
					if (read == -1) {
						listener.onFail(file);
						break;
					}
					outputStream.write(buf, 0, read);
					readSize += read;
					LogUtil.d("readSize:" + readSize + " totalSize:" + totalSize);
					listener.onProgress(readSize, totalSize, readSize == totalSize ? true : false);
				}
				listener.onSucess(file);
			} catch (Exception e) {
				LogUtil.d(e.getMessage());
				listener.onFail(file);
				e.printStackTrace();
			} finally {
				LogUtil.d("下载结束");
				try {
					if (inputStream != null)
						inputStream.close();
					if (outputStream != null)
						outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
